package com.gupaoedu.vip.mongo.transaction;

import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.Arrays;

public class TransactionTest {

    public static void main(String[] args) {

        com.mongodb.client.MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
        MongoDatabase db = mongoClient.getDatabase("testDB_Java_tx");
        ClientSession session = mongoClient.startSession();
        try {
            session.startTransaction();

            MongoCollection<Document> member = db.getCollection("t_member");

            Document document = new Document("name", "TomTest")
                    .append("type", "database")
                    .append("count", 1)
                    .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
                    .append("info", new Document("x", 203).append("y", 102));
            member.insertOne(document);

            MongoCollection<Document> user = db.getCollection("t_user");
            Document document1 = new Document("name", "MongoDB")
                    .append("type", "database")
                    .append("count", 1 / 0)
                    .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
                    .append("info", new Document("x", 203).append("y", 102));
            user.insertOne(document1);

            session.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            session.abortTransaction();
        } finally {
            session.close();
        }
    }
}
